package com.top75;

import com.bean.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author: huangzhigao
 * @Date: 2023/5/23 20:51
 */
public class Code1161 {
    public int maxLevelSum(TreeNode root) {
        if (root == null) {
            return 0;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int res = 0;
        int level = 1;
        int max = Integer.MIN_VALUE;
        while (!queue.isEmpty()) {
            int levelCount = 0;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                levelCount += poll.val;
                if (poll.left != null) {
                    queue.offer(poll.left);
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                }
            }
            if (levelCount > max) {
                res = level;
                max = levelCount;
            }

            level++;
        }
        return res;
    }
}
